package com.xhorse.lockplatform.manage.controller;

import com.xhorse.lockplatform.comm.constant.ConstantDefineUtil;
import com.xhorse.lockplatform.comm.constant.FilePathDefine;
import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.BaseMessage;
import com.xhorse.lockplatform.model.XhAppUpdateInfo;
import com.xhorse.lockplatform.model.XhLogFile;
import com.xhorse.lockplatform.service.AppUpdateInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("AppVersion")
public class AppVersionController {

    @Autowired
    private AppUpdateInfoService getUpdateInfoService;

    @RequestMapping("/upload")
    public String upload() {
        return "AppVersion/upload";
    }

    @RequestMapping("/getlog")
    public String getlog() {
        return "AppVersion/getlog";
    }

    @RequestMapping("/appInfoList")
    public String appInfoList() {
        return "AppVersion/appInfoList";
    }

    /**
     * app版本更新提交
     *
     * @param multipartFile
     * @param xhAppUpdateInfo
     * @return
     */
    @RequestMapping(value = "/AppUpdateInfoUpload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> AppUpdateInfoUpload(HttpServletRequest request, MultipartFile multipartFile,
                                                   XhAppUpdateInfo xhAppUpdateInfo,
                                                   @RequestParam("updataLog") String[] updataLog,
                                                   @RequestParam("languageId") String[] languageId) {
        BaseMessage baseMessage = new BaseMessage();
        try {
            // 获取文件名称作为保存到服务器的文件名称
            String filename = multipartFile.getOriginalFilename();
            if (filename != "") {
                xhAppUpdateInfo.setFileName(filename);
                // 前半部分路径，目录，将WebContent下的一个名称为images文件夹转换成绝对路径
                File file = new File(FilePathDefine.APK_DOWNLOAD_PATH, filename);
                multipartFile.transferTo(file);
            }
            // 将更新信息同步到数据库
            for (int i = 0; i < updataLog.length; i++) {
                xhAppUpdateInfo.setUpdataLog(updataLog[i]);
                xhAppUpdateInfo.setLanguageId(Integer.valueOf(languageId[i]));
                getUpdateInfoService.updateInfo(xhAppUpdateInfo);
            }
            // 上述操作成功，则返回成功信息
            baseMessage.putStatus(ConstantDefineUtil.STATUS.get("SUCCESS"));
        } catch (Exception e) {
            throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "AppUpdateInfoUpload ,遇到异常", e);
        }
        return baseMessage.baseMsg;
    }

    /**
     * 获取该客户下的所有log文件
     *
     * @param model
     * @param customerId
     * @return
     */
    @RequestMapping(value = "/getLogFileUrl", method = RequestMethod.POST)
    public String getLogFileUrl(Model model, HttpServletRequest request, String customerId) {
        File fileDirectory;
        List<XhLogFile> list = new ArrayList<>();
        if (customerId == null || customerId.equals("")) {
            fileDirectory = new File(FilePathDefine.TEST_LOG_PATH);
            if (fileDirectory.exists()) {
                File[] filelist = fileDirectory.listFiles(); // 获取文件夹下文件列表
                for (File file : filelist) {
                    if (file.isFile()) {
                        continue;
                    }
                    XhLogFile temp = new XhLogFile();
                    List<String> fileList = new ArrayList<String>();
                    temp.setCustomerId(file.getName());
                    File[] subFilelist = file.listFiles();
                    for (File subFile : subFilelist) {
                        fileList.add(subFile.getName());
                    }
                    temp.setLogFileList(fileList);
                    list.add(temp);
                }
            }
        } else {
            fileDirectory = new File(FilePathDefine.TEST_LOG_PATH + customerId + "\\");
            if (fileDirectory.exists()) {
                File[] filelist = fileDirectory.listFiles(); // 获取文件夹下文件列表
                XhLogFile temp = new XhLogFile();
                List<String> fileList = new ArrayList<>();
                for (File file : filelist) {
                    temp.setCustomerId(customerId);
                    fileList.add(file.getName());
                }
                temp.setLogFileList(fileList);
                list.add(temp);
            }
        }
        model.addAttribute("list", list);
        model.addAttribute("customerId", customerId);
        return "AppVersion/getlog";
    }

    /**
     * 下载日志文件
     *
     * @param customerId
     * @param fileName
     * @param response
     */
    @RequestMapping(value = "/logFileDownload", method = {RequestMethod.POST,
            RequestMethod.GET})
    public void logFileDownload(String customerId, String fileName, HttpServletRequest request,
                                HttpServletResponse response) {
        File file = new File(FilePathDefine.TEST_LOG_PATH + customerId + "\\" + fileName);
        if (file.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setContentType("application/octet-stream;charset=UTF-8");
                fis = new FileInputStream(file);
                os = response.getOutputStream();
                byte[] b = new byte[1024 * 1024];
                int index;
                while ((index = fis.read(b)) != -1) {
                    os.write(b, 0, index);
                }
            } catch (FileNotFoundException e) {
                throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "logFileDownload FileNotFoundException，遇到异常", e);
            } catch (IOException e) {
                throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "logFileDownload IOException，遇到异常", e);
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "logFileDownload IOException，遇到异常", e);
                }
            }

        }
    }

    /**
     * 获取app版本列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUpdateInfoList", method = RequestMethod.POST)
    public String getUpdateInfoList(Model model, HttpServletRequest request) {
        int type = Integer.valueOf(request.getParameter("type"));
        List<XhAppUpdateInfo> list = getUpdateInfoService.getAppInfoList(type);
        model.addAttribute("list", list);
        model.addAttribute("type", type);
        return "AppVersion/appInfoList";

    }

    /**
     * 删除app版本信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteUpdateInfo", method = {RequestMethod.POST,
            RequestMethod.GET})
    public String deleteUpdateInfo(Model model, HttpServletRequest request, int id, int type) {
        int result = getUpdateInfoService.deleteUpdateInfo(id);
        List<XhAppUpdateInfo> list = getUpdateInfoService.getAppInfoList(type);
        model.addAttribute("list", list);
        if (result > 0) {
            return "AppVersion/appInfoList";
        } else {
            return "500";
        }
    }

    /**
     * 获取最近app和固件版本
     *
     * @param type
     * @return
     */
    @RequestMapping(value = "/getLatestAppDeviceVer", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getLatestAppDeviceVer(HttpServletRequest request, int type, int regionId) {
        BaseMessage baseMessage = new BaseMessage();
        Map<String, String> result = getUpdateInfoService
                .getLatestAppDeviceVer(request, type, regionId);
        baseMessage.putData(result);
        baseMessage.putStatus(ConstantDefineUtil.STATUS.get("SUCCESS"));
        return baseMessage.baseMsg;
    }

}
